package com.test.chatdemo.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.QuadCurve2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

/**
 * 验证码图片生成工具类
 */
public class CaptchaUtil {

    // 验证码字符集
    private static final char[] CHARS = {
            '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };

    // 随机数生成器
    private static final Random RANDOM = new Random();

    /**
     * 生成验证码图片的Base64字符串
     * @param code 验证码文本
     * @return Base64编码的图片字符串
     */
    public static String generateCaptchaImage(String code) {
        // 图片宽度和高度
        int width = 120;
        int height = 40;

        // 创建BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取Graphics2D
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 24));

        // 绘制验证码字符
        for (int i = 0; i < code.length(); i++) {
            // 随机颜色
            g.setColor(getRandomColor());
            // 绘制字符
            g.drawString(String.valueOf(code.charAt(i)), 20 + i * 20, 28);
        }

        // 绘制干扰线
        drawInterferenceLines(g, width, height);

        // 绘制噪点
        drawNoise(image, width, height);

        g.dispose();

        // 转换为Base64
        return imageToBase64(image);
    }

    /**
     * 生成随机颜色
     */
    private static Color getRandomColor() {
        return new Color(
                RANDOM.nextInt(180),
                RANDOM.nextInt(180),
                RANDOM.nextInt(180)
        );
    }

    /**
     * 绘制干扰线
     */
    private static void drawInterferenceLines(Graphics2D g, int width, int height) {
        for (int i = 0; i < 5; i++) {
            g.setColor(getRandomColor());
            int x1 = RANDOM.nextInt(width);
            int y1 = RANDOM.nextInt(height);
            int x2 = RANDOM.nextInt(width);
            int y2 = RANDOM.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }
    }

    /**
     * 绘制噪点
     */
    private static void drawNoise(BufferedImage image, int width, int height) {
        for (int i = 0; i < 100; i++) {
            int x = RANDOM.nextInt(width);
            int y = RANDOM.nextInt(height);
            image.setRGB(x, y, getRandomColor().getRGB());
        }
    }

    /**
     * 将图片转换为Base64字符串
     */
    private static String imageToBase64(BufferedImage image) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "JPEG", baos);
            byte[] imageBytes = baos.toByteArray();
            return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(imageBytes);
        } catch (IOException e) {
            throw new RuntimeException("生成验证码图片失败", e);
        }
    }

    /**
     * 生成随机验证码
     */
    public static String generateRandomCode(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(CHARS[RANDOM.nextInt(CHARS.length)]);
        }
        return sb.toString();
    }

    // 在CaptchaUtil中添加这个方法
    public static String generateAdvancedCaptchaImage(String code) {
        int width = 130;
        int height = 48;

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 设置背景渐变
        GradientPaint gradient = new GradientPaint(0, 0, Color.LIGHT_GRAY, width, height, Color.WHITE);
        g.setPaint(gradient);
        g.fillRect(0, 0, width, height);

        // 设置字体（随机选择字体）
        String[] fontNames = {"Arial", "Verdana", "Georgia", "Times New Roman"};
        Font font = new Font(fontNames[RANDOM.nextInt(fontNames.length)], Font.BOLD | Font.ITALIC, 28 + RANDOM.nextInt(5));
        g.setFont(font);

        // 绘制字符（带旋转和扭曲）
        for (int i = 0; i < code.length(); i++) {
            g.setColor(getRandomColor());

            // 随机旋转角度
            double angle = Math.PI / 4 * RANDOM.nextDouble() - Math.PI / 8;
            g.rotate(angle, 25 + i * 25, 30);

            // 绘制字符
            g.drawString(String.valueOf(code.charAt(i)), 20 + i * 25, 30 + RANDOM.nextInt(5));

            // 恢复旋转
            g.rotate(-angle, 25 + i * 25, 30);
        }

        // 绘制干扰线
        drawAdvancedInterferenceLines(g, width, height);

        // 添加边框
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, width - 1, height - 1);

        g.dispose();

        return imageToBase64(image);
    }

    private static void drawAdvancedInterferenceLines(Graphics2D g, int width, int height) {
        g.setStroke(new BasicStroke(1.5f));
        for (int i = 0; i < 8; i++) {
            g.setColor(getRandomColor());
            int x1 = RANDOM.nextInt(width / 2);
            int y1 = RANDOM.nextInt(height);
            int x2 = RANDOM.nextInt(width / 2) + width / 2;
            int y2 = RANDOM.nextInt(height);

            // 贝塞尔曲线
            int ctrlX = RANDOM.nextInt(width);
            int ctrlY = RANDOM.nextInt(height);

            QuadCurve2D curve = new QuadCurve2D.Float(x1, y1, ctrlX, ctrlY, x2, y2);
            g.draw(curve);
        }
    }

}